<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>量表发布测试</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-bug me-2"></i>量表发布题目重复问题测试</h5>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <h6><i class="bi bi-info-circle me-2"></i>测试说明</h6>
                            <p class="mb-0">此页面用于测试量表发布时题目数量翻倍的问题是否已修复。</p>
                        </div>

                        <div class="mb-4">
                            <h6>Token 状态</h6>
                            <div class="d-flex gap-2 mb-3">
                                <button class="btn btn-outline-primary btn-sm" onclick="checkToken()">检查 Token</button>
                                <button class="btn btn-outline-warning btn-sm" onclick="clearToken()">清除 Token</button>
                                <button class="btn btn-outline-success btn-sm" onclick="setTestToken()">设置测试 Token</button>
                            </div>
                            <div id="token-status" class="alert alert-secondary">未检查</div>
                        </div>

                        <div class="mb-4">
                            <h6>测试步骤</h6>
                            <ol>
                                <li>确保已登录（设置测试Token）</li>
                                <li>创建一个包含2道题目的量表</li>
                                <li>发布量表</li>
                                <li>检查题目数量是否仍为2道（而不是4道）</li>
                                <li>再次发布，检查题目数量是否仍为2道（而不是6道）</li>
                            </ol>
                        </div>

                        <div class="mb-4">
                            <h6>测试操作</h6>
                            <div class="d-flex gap-2 mb-3">
                                <button class="btn btn-primary" onclick="createTestScale()">创建测试量表</button>
                                <button class="btn btn-success" onclick="publishTestScale()" id="publish-btn" disabled>发布量表</button>
                                <button class="btn btn-info" onclick="checkScaleQuestions()" id="check-btn" disabled>检查题目数量</button>
                            </div>
                            <div id="test-results" class="alert alert-secondary">等待操作...</div>
                        </div>

                        <div class="mb-4">
                            <h6>快速链接</h6>
                            <div class="d-flex gap-2">
                                <a href="http://127.0.0.1:5000/members/scale-creator" class="btn btn-outline-primary btn-sm" target="_blank">
                                    <i class="bi bi-plus-circle me-1"></i>创建量表
                                </a>
                                <a href="http://127.0.0.1:5000/members/my-scales" class="btn btn-outline-info btn-sm" target="_blank">
                                    <i class="bi bi-list me-1"></i>我的量表
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let testScaleId = null;

        // 复制 apiRequest 函数
        async function apiRequest(url, options = {}) {
            const token = localStorage.getItem('access_token');
            
            const defaultOptions = {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    ...(token && { 'Authorization': `Bearer ${token}` })
                }
            };
            
            const finalOptions = { ...defaultOptions, ...options };
            
            try {
                const response = await fetch(`http://127.0.0.1:5000${url}`, finalOptions);
                const data = await response.json();
                
                if (!response.ok) {
                    throw new Error(data.message || `HTTP ${response.status}`);
                }
                
                return data;
            } catch (error) {
                console.error('API请求失败:', error);
                throw error;
            }
        }

        function checkToken() {
            const token = localStorage.getItem('access_token');
            const statusDiv = document.getElementById('token-status');
            
            if (token) {
                // 验证token有效性
                apiRequest('/api/auth/verify')
                    .then(response => {
                        if (response.success) {
                            statusDiv.className = 'alert alert-success';
                            statusDiv.innerHTML = `<i class="bi bi-check-circle me-2"></i>Token 有效，用户: ${response.data.username}`;
                        } else {
                            statusDiv.className = 'alert alert-danger';
                            statusDiv.innerHTML = `<i class="bi bi-x-circle me-2"></i>Token 无效`;
                        }
                    })
                    .catch(error => {
                        statusDiv.className = 'alert alert-danger';
                        statusDiv.innerHTML = `<i class="bi bi-x-circle me-2"></i>Token 验证失败: ${error.message}`;
                    });
            } else {
                statusDiv.className = 'alert alert-warning';
                statusDiv.innerHTML = '<i class="bi bi-exclamation-triangle me-2"></i>未找到 Token';
            }
        }

        function clearToken() {
            localStorage.removeItem('access_token');
            document.getElementById('token-status').className = 'alert alert-secondary';
            document.getElementById('token-status').innerHTML = 'Token 已清除';
        }

        function setTestToken() {
            // 设置一个测试用的token（需要根据实际情况调整）
            const testToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTcyMjMzNzM2MiwianRpIjoiYzQwZWY4YzMtNGY0Zi00YzI5LWI4YzMtZjU5ZjE2YzQwZjI5IiwidHlwZSI6ImFjY2VzcyIsInN1YiI6eyJpZCI6NywidXNlcm5hbWUiOiJ0ZXN0dXNlciIsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSIsInJvbGUiOiJtZW1iZXIifSwibmJmIjoxNzIyMzM3MzYyLCJleHAiOjE3MjIzNDA5NjJ9.example';
            localStorage.setItem('access_token', testToken);
            checkToken();
        }

        async function createTestScale() {
            const resultsDiv = document.getElementById('test-results');
            resultsDiv.className = 'alert alert-info';
            resultsDiv.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>正在创建测试量表...';

            try {
                // 创建量表
                const scaleData = {
                    title: `测试量表 ${new Date().getTime()}`,
                    subtitle: '题目重复问题测试',
                    description: '用于测试量表发布时题目数量是否会翻倍的测试量表',
                    instruction: '请根据实际情况选择答案',
                    category_id: 1,
                    author: '测试用户',
                    version: '1.0',
                    is_public: true,
                    is_free: true,
                    price: 0
                };

                const createResponse = await apiRequest('/api/scales/create', {
                    method: 'POST',
                    body: JSON.stringify(scaleData)
                });

                if (createResponse.success) {
                    testScaleId = createResponse.data.id;
                    
                    // 添加2道测试题目
                    const questions = [
                        {
                            question_text: '测试题目1：您对当前的心理状态满意吗？',
                            question_type: 'single',
                            is_required: true,
                            options: [
                                { option_text: '非常满意', option_value: 5 },
                                { option_text: '比较满意', option_value: 4 },
                                { option_text: '一般', option_value: 3 },
                                { option_text: '不太满意', option_value: 2 },
                                { option_text: '非常不满意', option_value: 1 }
                            ]
                        },
                        {
                            question_text: '测试题目2：您最近的睡眠质量如何？',
                            question_type: 'single',
                            is_required: true,
                            options: [
                                { option_text: '很好', option_value: 5 },
                                { option_text: '较好', option_value: 4 },
                                { option_text: '一般', option_value: 3 },
                                { option_text: '较差', option_value: 2 },
                                { option_text: '很差', option_value: 1 }
                            ]
                        }
                    ];

                    // 添加题目
                    for (let i = 0; i < questions.length; i++) {
                        const questionData = {
                            ...questions[i],
                            question_number: i + 1
                        };
                        
                        await apiRequest(`/api/scales/${testScaleId}/questions`, {
                            method: 'POST',
                            body: JSON.stringify(questionData)
                        });
                    }

                    resultsDiv.className = 'alert alert-success';
                    resultsDiv.innerHTML = `<i class="bi bi-check-circle me-2"></i>测试量表创建成功！量表ID: ${testScaleId}，包含 ${questions.length} 道题目`;
                    
                    document.getElementById('publish-btn').disabled = false;
                    document.getElementById('check-btn').disabled = false;
                } else {
                    throw new Error(createResponse.message);
                }
            } catch (error) {
                resultsDiv.className = 'alert alert-danger';
                resultsDiv.innerHTML = `<i class="bi bi-x-circle me-2"></i>创建失败: ${error.message}`;
            }
        }

        async function publishTestScale() {
            if (!testScaleId) {
                alert('请先创建测试量表');
                return;
            }

            const resultsDiv = document.getElementById('test-results');
            resultsDiv.className = 'alert alert-info';
            resultsDiv.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>正在发布量表...';

            try {
                const publishResponse = await apiRequest(`/api/scales/${testScaleId}/publish`, {
                    method: 'POST'
                });

                if (publishResponse.success) {
                    resultsDiv.className = 'alert alert-success';
                    resultsDiv.innerHTML = '<i class="bi bi-check-circle me-2"></i>量表发布成功！现在可以检查题目数量。';
                    
                    // 自动检查题目数量
                    setTimeout(checkScaleQuestions, 1000);
                } else {
                    throw new Error(publishResponse.message);
                }
            } catch (error) {
                resultsDiv.className = 'alert alert-danger';
                resultsDiv.innerHTML = `<i class="bi bi-x-circle me-2"></i>发布失败: ${error.message}`;
            }
        }

        async function checkScaleQuestions() {
            if (!testScaleId) {
                alert('请先创建测试量表');
                return;
            }

            const resultsDiv = document.getElementById('test-results');
            resultsDiv.className = 'alert alert-info';
            resultsDiv.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>正在检查题目数量...';

            try {
                const questionsResponse = await apiRequest(`/api/scales/${testScaleId}/questions`);

                if (questionsResponse.success) {
                    const questionCount = questionsResponse.data.questions.length;
                    const expectedCount = 2;
                    
                    if (questionCount === expectedCount) {
                        resultsDiv.className = 'alert alert-success';
                        resultsDiv.innerHTML = `<i class="bi bi-check-circle me-2"></i>✅ 测试通过！题目数量正确: ${questionCount} 道题目（期望: ${expectedCount} 道）`;
                    } else {
                        resultsDiv.className = 'alert alert-danger';
                        resultsDiv.innerHTML = `<i class="bi bi-x-circle me-2"></i>❌ 测试失败！题目数量异常: ${questionCount} 道题目（期望: ${expectedCount} 道）`;
                    }
                    
                    // 显示题目详情
                    let detailsHtml = '<br><strong>题目详情:</strong><ul>';
                    questionsResponse.data.questions.forEach((q, index) => {
                        detailsHtml += `<li>题目 ${q.question_number}: ${q.question_text}</li>`;
                    });
                    detailsHtml += '</ul>';
                    resultsDiv.innerHTML += detailsHtml;
                } else {
                    throw new Error(questionsResponse.message);
                }
            } catch (error) {
                resultsDiv.className = 'alert alert-danger';
                resultsDiv.innerHTML = `<i class="bi bi-x-circle me-2"></i>检查失败: ${error.message}`;
            }
        }

        // 页面加载时检查token状态
        window.onload = function() {
            checkToken();
        };
    </script>
</body>
</html>